from DatabaseConnector import leaves
from SyntaxParser import buildFindingsHash
import MySQLdb

class Diagnosis:
	def __init__(self, diagnosis):
		self.diagnosis = diagnosis
	
	def sql_connect(self, database):
	    try:
	        ## You may have to change the username and password.
	        ##
	        connection = MySQLdb.connect(host="localhost",
	                                     user="root", passwd="notroot",port=3406,
	                                     db=database )
	        return connection
	
	    except MySQLdb.OperationalError, message:
	        errorMessage = "Error %d:\n%s" % (message[ 0 ], message[ 1 ] )
	        print errorMessage
	
	#return an array of pids satisfying diagnosis input        	
	def getDiagnosisPidArray(self):
		connection1 = self.sql_connect("patient_concept")
		connection2 = self.sql_connect("snomed")
		diagnosis_pid_array = None
		concept_id_array = []

		diagnosis = self.diagnosis.lower().strip()
		if diagnosis == '':
			return None
		"""	
		#input->1. IS snomed finding -> get corres. conceptid and subhierarchies -> return pid from patient_concept
		#		2. IS NOT snomed finding -> get snomed finding containing input -> get conceptid and subhierarchies conceptid ->return pid from patient_concept
                """
		has_error = 0
		error = ''
		
		query_getConceptId = "SELECT concept_id FROM concept_term WHERE term = \"" + diagnosis + "\""
		cursor_getConceptId = connection2.cursor()
		cursor_getConceptId.execute(query_getConceptId)
		concept_ids = cursor_getConceptId.fetchall()
		cursor_getConceptId.close()
		
		if len(concept_ids) == 0:
			print "Diagnosis input is not a valid concept"
		else:
			for conceptId in concept_ids:
				conceptId = conceptId[0]
				concept_id_array.append(conceptId)
				subhierarchies_string = leaves(conceptId).strip()
				print str(conceptId) + subhierarchies_string
				if subhierarchies_string.endswith("|"):
					subhierarchies_string = subhierarchies_string[0:len(subhierarchies_string)-1]
				
				subhierarchies_array = subhierarchies_string.split("|")
				for subhierarchy in subhierarchies_array:
                                    concept_id_array.append(subhierarchy)
					
			query_getPid = "SELECT DISTINCT pid FROM patient_concept WHERE concept_id IN ('" + str(concept_id_array[0]) + "'"
			for i in range(1, len(concept_id_array)):
				query_getPid = query_getPid + ", '" + str(concept_id_array[i]) + "'"
			query_getPid += ")"

			cursor_getPid = connection1.cursor()
                        cursor_getPid.execute(query_getPid)
                        diagnosis_pid_array = cursor_getPid.fetchall()
                        cursor_getPid.close()
		    
		return diagnosis_pid_array  

	"""
	#return an array of pids satisfying diagnosis input        	
	def getCurrDiagnosisPidArray(self):
		connection = self.sql_connect("patient_concept")
		curr_diagnosis_pid_array = None
		
		curr_diagnosis = self.curr_diagnosis.lower().strip()
		if curr_diagnosis == '':
			return None
			
		#input->1. IS snomed finding -> get corres. conceptid and subhierarchies -> return pid from patient_concept
		#		2. IS NOT snomed finding -> get snomed finding containing input -> get conceptid and subhierarchies conceptid ->return pid from patient_concept
		findings_path = 'doc/snomed/findings.txt'
		findings = buildFindingsHash(findings_path)
		findings_array = findings.keys()
		has_error = 0
		error = ''
		
		try:
			findings_array.index(curr_diagnosis)
			conceptId = findings.get(curr_diagnosis)
		except ValueError:
			has_term = 0
			for finding in findings_array:
				if finding.find(curr_diagnosis) != -1:
					conceptId = findings.get(finding)
					has_term = 1
					break
			if has_term == 0:
				error = "Current diagnosis input is not a valid concept"
				has_error = 1
		
		if has_error == 1:
			print error
		else:
			subhierarchies_string = leaves(conceptId).strip()
			if subhierarchies_string.endswith("|"):
				subhierarchies_string = subhierarchies_string[0:len(subhierarchies_string)-1]
			
			subhierarchies_array = subhierarchies_string.split("|")
			query_getPid = "SELECT DISTINCT pid FROM curr_patient_concept WHERE concept_id IN ('" + conceptId + "'"
			for subhierarchy in subhierarchies_array:
				query_getPid = query_getPid + ", '" + subhierarchy + "'"
			query_getPid += ")"
			
			cursor_getPid = connection.cursor()
                        cursor_getPid.execute(query_getPid)
                        curr_diagnosis_pid_array = cursor_getPid.fetchall()
                        cursor_getPid.close()
		    
		return curr_diagnosis_pid_array
	    """
